package com.leetcode.partition1;

/**
 * @author `RKC`
 * @date 2021/8/4 9:17
 */
public class LC35搜索插入位置 {

    public static int searchInsert(int[] nums, int target) {
        return binarySearch(nums, target);
    }

    public static void main(String[] args) {
        int[] nums = { 1, 3, 5, 6 };
        System.out.println(searchInsert(nums, 2));
    }

    //二分法
    public static int binarySearch(int[] nums, int target) {
        if (nums.length == 0) return 0;
        int left = 0, right = nums.length - 1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid;
            } else {
                return mid;
            }
        }
        return nums[left] < target ? left + 1 : left;
    }

    //常规法
    public static int iteration(int[] nums, int target) {
        if (nums.length == 0) return 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > target || nums[i] == target) {
                return i;
            }
        }
        return nums.length;
    }
}
